/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.logic;

import java.sql.Blob;
import java.util.List;
import org.mags.common.EngineContext;
import org.mags.remas.model.entity.EntityFile;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

/**
 * 
 * @author Mario Gaitan
 *
 */
public final class EntityFileUtils {
	private EntityFileUtils(){}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List<EntityFile> getFiles(final Object[] ids) {
		return (List<EntityFile>)EngineContext.getDataContext().getTransactionTemplate().execute(new TransactionCallback() {
			public Object doInTransaction(TransactionStatus status) {
				List<EntityFile> entityFiles = EngineContext.getDataContext().getEntityProviderFactory().getEntityFileProvider().getByEntityIds(ids);
				for(EntityFile entityFile: entityFiles) {
					Blob content = entityFile.getContent();
					if(content!=null) {
						try {							
							entityFile.setRawContent(content.getBytes(1, (int) content.length()));
						} catch (Exception e) {
							if(e instanceof RuntimeException)
								throw (RuntimeException)e;
							else
								throw new RuntimeException(e);
						}
					}
				}
				return entityFiles;
			}
		});						
	}
	public static List<EntityFile> getFiles(long entityId) {
		return getFiles(new Object[]{entityId});
	}
}
